import dayjs from "dayjs";
// 获取应用实例
const app = getApp();
// import { hundreds } from "../../../static/js/loveData";
// 初始化数据库
const db = wx.cloud.database();
const uimg = db.collection("uimg");

let flag = false;
// pages/hundred/hundred.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    theme: 1,
    openid: "",
    o_openid: '',
    hundredList: [],
    page: 0,
    loading: false,
    noMore: true,
    isLoading: false,
    punchImg: '',
    punchId: '',
    fileID: '',
    actionSheet: false,
    punchInfo: {
      id: '',
      title: '',
      state: ''
    },

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,
  },

  // 上滑加载
  // scrollTolower() {
  //   if (flag != false) return;
  //   flag = true;
  //   let { page } = this.data;
  //   page += 20;
  //   this.setData({
  //     page,
  //     loading: true,
  //   });
  //   if (page >= 100) {
  //     this.setData({ page: 0, noMore: true, loading: false });
  //   } else {
  //     setTimeout(() => {
  //       this.getHundredData(page);
  //       this.setData({
  //         loading: false,
  //       });
  //       flag = false;
  //     }, 1500);
  //   }
  // },

  // 获取数据
  // getHundredData(page) {
  //   wx.showLoading({
  //     title: "Loading...",
  //   });
  //   let {
  //     // page,
  //     hundredList,
  //   } = this.data;
  //   hundred
  //     .limit(20)
  //     .skip(page)
  //     .get({
  //       success: (res) => {
  //         console.log(res);

  //         hundredList = hundredList.concat(res.data);
  //         this.setData({
  //           hundredList,
  //         });
  //         wx.hideLoading();
  //         // wx.hideNavigationBarLoading();
  //         wx.stopPullDownRefresh();
  //         wx.showToast({
  //           title: "加载成功",
  //           icon: "success",
  //         });
  //       },
  //       catch: () => {
  //         wx.showToast({
  //           title: "获取失败",
  //           icon: "none",
  //         });
  //       },
  //     });
  // },

  getHundredData(openid) {
    let { hundredList, o_openid } = this.data;
    if (!o_openid) {
      wx.showModal({
        title: '绑定提醒',
        content: '你还没有绑定情侣，是否现在去绑定？',
        complete: (res) => {
          if (res.cancel) {
            wx.navigateBack();
          }
          if (res.confirm) {
            wx.navigateTo({
              url: '/packageMine/pages/invitecode/invitecode',
            })
          }
        }
      })
      return;
    }
    wx.showLoading({
      title: "Loading...",
    });
    uimg.where({ _openid: openid }).get({
      success: (res) => {
        hundredList = res.data[0].hundred;
        this.setData({
          hundredList,
          isLoading: false,
        });
      },
      fail: () => {
        wx.showToast({
          title: "获取失败",
          icon: "none",
        });
      },
      complete: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      },
    });
  },
  handleActionSheet(e) {
    const { id, title, state, img, fileid } = e.currentTarget.dataset;
    let { actionSheet, punchInfo, punchImg, fileID } = this.data;
    punchInfo.id = id;
    punchInfo.title = title;
    punchInfo.state = state;
    punchInfo.img = img;
    punchInfo.fileID = fileid;

    if (punchImg) {
      wx.cloud.deleteFile({
        fileList: [fileID],
        success(res) {
          console.log(res, '删除文件')
        },
        fail(err) {
          console.log(err)
        }
      });
    }

    this.setData({
      punchInfo,
      punchImg: '',
      actionSheet: !actionSheet
    })
  },
  punch(e) {
    const that = this;

    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        // console.log(res.tempFiles[0].tempFilePath)

        that.setData({
          punchImg: res.tempFiles[0].tempFilePath
        })
      }
    })
  },
  // updata(openid, o_openid) {
  //   const that = this;
  //   uimg.where({ _openid: openid }).update({
  //     data: {
  //       hundred: hundreds
  //     },
  //     success: () => {
  //       uimg.where({ _openid: o_openid }).update({
  //         data: {
  //           hundred: hundreds
  //         },
  //         success: () => { },
  //         fail: () => { },
  //         complete: () => { }
  //       })
  //     },
  //     fail: () => { },
  //     complete: () => { }
  //   })
  // },
  confirm() {
    const that = this;
    let { hundredList, openid, o_openid, punchInfo, punchImg } = that.data;
    if (punchImg == '') {
      wx.showToast({
        title: '请选择图片',
        icon: "none"
      })
      return;
    }
    wx.showToast({
      title: "图片上传中",
      icon: "loading"
    });
    wx.cloud.uploadFile({
      cloudPath: "hundred/hundred" + new Date().getTime() + ".png", // 上传至云端的路径
      filePath: punchImg, // 小程序临时文件路径
      success: (res) => {
        that.setData({
          fileID: res.fileID,
        });
        wx.cloud.getTempFileURL({
          fileList: [res.fileID],
          success: (ret) => {
            const url = ret.fileList[0].tempFileURL;
            console.log(url);
            hundredList.forEach((item) => {
              if (item.id == punchInfo.id) {
                if (item.state == "") {
                  item.state = true;
                  item.img = url;
                  item.fileID = res.fileID;
                  item.time = dayjs(new Date()).format("YYYY/MM/DD");
                } else {
                  item.state = "";
                  item.img = "";
                }
                return;
              }
            });
            uimg.where({ _openid: openid }).update({
              data: {
                hundred: hundredList
              },
              success: () => {
                uimg.where({ _openid: o_openid }).update({
                  data: {
                    hundred: hundredList
                  },
                  success: () => { },
                  fail: () => {
                    wx.showToast({
                      title: '打卡失败',
                      icon: "none"
                    })
                  },
                  complete: () => {
                    that.setData({
                      actionSheet: false,
                      punchImg: ''
                    })
                    that.getHundredData(openid);
                  }
                })
              },
              fail: () => {
                wx.showToast({
                  title: '上传失败',
                  icon: "none"
                })
                that.setData({
                  actionSheet: false
                })
                that.getHundredData(openid);
              },
              complete: () => { }
            })
          },
          fail: () => {
            wx.showToast({
              title: "上传失败",
              icon: "error",
            });
            wx.hideLoading();
            wx.hideNavigationBarLoading();
          },
        });
      },
      fail: () => {
        wx.showToast({
          title: "上传失败",
          icon: "error",
        });
        wx.hideLoading();
        wx.hideNavigationBarLoading();
      },
    });
  },
  cancel() {
    const that = this;
    let { hundredList, openid, o_openid, punchInfo } = that.data;
    wx.cloud.deleteFile({
      fileList: [punchInfo.fileID],
      success(res) {
        console.log(res, '删除文件')
      },
      fail(err) {
        console.log(err)
      }
    });
    hundredList.forEach((item) => {
      if (item.id == punchInfo.id) {
        item.state = "";
        item.img = "";
        item.fileID = "";
        return;
      }
    });
    uimg.where({ _openid: openid }).update({
      data: {
        hundred: hundredList
      },
      success: () => {
        uimg.where({ _openid: o_openid }).update({
          data: {
            hundred: hundredList
          },
          success: () => { },
          fail: () => {
            wx.showToast({
              title: '操作失败',
              icon: "none"
            })
          },
          complete: () => {
            that.setData({
              actionSheet: false
            })
            that.getHundredData(openid);
          }
        })
      },
      fail: () => {
        wx.showToast({
          title: '操作失败',
          icon: "none"
        })
        that.setData({
          actionSheet: false
        })
        that.getHundredData(openid);
      },
      complete: () => { }
    })
  },

  // 修改完成
  onClose(e) {
    const that = this;
    let { hundredList, openid, o_openid } = that.data;
    const { id } = e.currentTarget.dataset;
    const { position, instance } = e.detail;
    switch (position) {
      case "left":
        instance.close();
        break;
      case "cell":
        instance.close();
        break;
      case "right":
        hundredList.forEach((item) => {
          if (item.id == id) {
            if (item.state == "") {
              item.state = true;
            } else {
              item.state = "";
            }
            return;
          }
        });

        uimg.where({ _openid: openid }).update({
          data: {
            hundred: hundredList
          },
          success: () => {
            uimg.where({ _openid: o_openid }).update({
              data: {
                hundred: hundredList
              },
              success: () => { },
              fail: () => {
                wx.showToast({
                  title: '修改失败',
                  icon: "none"
                })
              },
              complete: () => {
                that.getHundredData(openid);
              }
            })
          },
          fail: () => {
            wx.showToast({
              title: '修改失败',
              icon: "none"
            })
            that.getHundredData(openid);
          },
          complete: () => { }
        })
        instance.close();
        break;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const openid = wx.getStorageSync("openid");
    const o_openid = wx.getStorageSync("o_openid");
    this.setData({
      page: 0,
      theme: app.globalData.theme,
      openid,
      o_openid
    });
    // this.getHundredData(this.data.page);
    this.getHundredData(openid);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // this.setData({
    //   hundredList: [],
    //   page: 0,
    //   loading: false,
    //   noMore: false,
    // });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // this.setData({
    //   hundredList: [],
    //   page: 0,
    //   loading: false,
    //   noMore: false,
    // });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const { openid } = this.data;
    this.setData({
      isLoading: true,
    });
    wx.showLoading({
      title: "Loading...",
    });
    this.getHundredData(openid);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
